<?php

declare(strict_types=1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class UserCheckin extends Model
{
  //

  public static function isCheckin($user_id = null, $days = null, $month = null)
  {

    if (is_null($user_id)) {
      $current_user = User::getCurrentUser();

      if (!is_null($current_user)) {
        $user_id = $current_user->id;
      }
    }

    if (is_null($days)) {
      $days = date('d');
    }
    if (is_null($month)) {
      $month = date('m');
    }

    $model_checkin = UserCheckin::where('user_id', $user_id)
      ->where('create_time', '>', mktime(0, 0, 0, (int)$month, (int)$days))
      ->where('create_time', '<', mktime(23, 59, 59, (int)$month, (int)$days))
      ->find();

    if (empty($model_checkin)) {
      return false;
    }
    return $model_checkin;
  }

  public static function checkin($user_id = null, $time = null)
  {
    $user = null;
    if (is_null($user_id)) {
      $current_user = User::getCurrentUser();

      if (!is_null($current_user)) {
        $user_id = $current_user->id;
        $user = $current_user;
      }
    }

    if (is_null($user)) {
      $user = User::find($user_id);
    }

    if (is_null($time)) {
      $time = time();
    }

    $model_checkin = new UserCheckin();

    $model_checkin->user_id = $user_id;
    $model_checkin->create_time = $time;

    $is_last_checkin = self::isCheckin($user_id, date('d') - 1);

    if ($is_last_checkin !== false) {
      $model_checkin->last_times = $is_last_checkin->last_times + 1;
    } else {
      $model_checkin->last_times = 1;
    }

    $model_checkin->save();

    $user->total_checkin_times++;
    $user->save();

    Vip::scanUser($user);

    UserCreditRecord::optionCheckin($user_id, $model_checkin->last_times);

    return $model_checkin;
  }
}
